<template>
	<view class="base-page-white yangsf-flex-col">
		<view class="yangsf-ratio-w-100">
			<view class="from-title">
				<image src="/static/icon/sx.png"></image>
				<span class="from-title-text">对方姓名({{prompt}})</span>
			</view>
			<view class="from-item">
				<view class="yangsf-ratio-h-40 yangsf-flex-col-center" @click="toAddUserPage">
					<u--input v-model="contract.userName" inputAlign="center" placeholder="填写正确才能生效" border="bottom"
						readonly suffixIcon="arrow-right"></u--input>
				</view>
			</view>
		</view>
		<view class="yangsf-ratio-w-100">
			<view class="from-title">
				<image src="/static/icon/sx.png"></image>
				<span class="from-title-text">借款金额</span>
			</view>
			<view class="from-item">
				<view class="yangsf-ratio-h-40">
					<u-number-box integer v-model="contract.money" @change="valChange" :min="0" :step="100"
						button-size="18" inputWidth="100"></u-number-box>
				</view>
			</view>
		</view>

		<view class="yangsf-ratio-w-100">
			<view class="from-title">
				<image src="/static/icon/sx.png"></image>
				<span class="from-title-text">借款利率(年化利率)</span>
			</view>
			<view class="from-item">
				<view class="yangsf-ratio-h-40" @click="showRates = true">
					<u-picker :show="showRates" :columns="rates" keyName="label" @confirm="confirmRates"
						@close="closeRates" @cancel="closeRates"></u-picker>
					<span style="color: #5B86E5; font-size: 36rpx;">{{contract.moneyRate}}%</span>
				</view>
			</view>
		</view>

		<view class="yangsf-ratio-w-100">
			<view class="from-title">
				<image src="/static/icon/sx.png"></image>
				<span class="from-title-text">借款时间</span>
			</view>
			<view class="from-item">
				<view class="yangsf-ratio-h-40 yangsf-flex-col-center">
					<!-- <view class="yangsf-ratio-h-40 yangsf-flex-col-center" @click="selectLoanDate">
					<u-datetime-picker :show="showLoanDate" mode="date" @confirm="confirmLoanDate"
						@cancel="cancelLoanDate" :minDate="minLoanDate" :maxDate="maxLoanDate"></u-datetime-picker>
					 -->
					<u--input v-model="contract.loanDate" inputAlign="center" border="none" placeholder="借款日期"
						readonly></u--input>
				</view>
			</view>
		</view>

		<view class="yangsf-ratio-w-100">
			<view class="from-title">
				<image src="/static/icon/sx.png"></image>
				<span class="from-title-text">还款日</span>
			</view>
			<view class="from-item">
				<view class="yangsf-ratio-h-40 yangsf-flex-col-center" @click="selectDate">
					<u-datetime-picker :show="showData" mode="date" @confirm="confirmData"
						:minDate="Number(new Date().getTime() + 24 * 60 * 60 * 1000)"
						@cancel="cancelDate"></u-datetime-picker>
					<u--input v-model="contract.repayment" inputAlign="center" border="none" placeholder="还款日"
						@change="compute" readonly></u--input>
				</view>
			</view>
		</view>

		<view class="yangsf-ratio-w-100 yangsf-flex-col-center">
			<view class="yangsf-ratio-w-80 card_lx yangsf-flex-col-center">
				<view style="color: #c1c1c1;">
					<span>总还款金额：</span>
					<span>{{computedTotalMoney}}元</span>
				</view>
			</view>
		</view>

		<view class="yangsf-ratio-w-100">
			<view class="from-title">
				<image src="/static/icon/sx.png"></image>
				<span class="from-title-text">借款用途</span>
			</view>
			<view class="from-item">
				<view class="yangsf-ratio-h-40" @click="showPurpose = true">
					<u-picker :show="showPurpose" :columns="purposes" keyName="label" @confirm="confirmPurpose"
						@close="closePurpose" @cancel="closePurpose"></u-picker>
					<span :style="!purpose?'color:#c1c1c1':''">{{!purpose?'请选择':purpose}}</span>
				</view>
			</view>
		</view>

		<view v-if="!(contract.id && contract.signNo.id > 0)" class="yangsf-page-bottom-button yangsf-card">
			<view class="yangsf-flex-row-center">
				<view class="yangsf-ratio-w-80 ">
					<u-button type="primary" text="发起合同" @click="check"></u-button>
				</view>
			</view>
		</view>


		<u-modal :show="showPayPassword" title="支付密码" @confirm="confirm" :closeOnClickOverlay="true">
			<view class="">
				<u-code-input v-model="payPassword" :maxlength="6" dot></u-code-input>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		saveContract,
		checkPayPassword
	} from '@/config/api.js'
	import {
		purposes
	} from '@/config/config.js'
	export default {
		data() {
			return {
				isCheckPay: false,
				showPayPassword: false,
				payPassword: '',
				prompt: '',
				showRates: false,
				showData: false,
				showLoanDate: false,
				showPurpose: false,
				purpose: '',
				minLoanDate: Date.now(), // 最小日期为当前日期
				maxLoanDate: Date.now() + 90 * 24 * 60 * 60 * 1000, // 最大日期为当前日期后3个月
				contract: {
					userName: '',
					userCardNo: '',
					userTele: '',
					money: 1000,
					moneyRate: 0,
					kind: '',
					loanDate: uni.$u.timeFormat(Date.now(), 'yyyy-mm-dd'),
					repayment: '',

					isTag: 0,
					stages: 1
				},
				rates: [
					[{
						label: '0%',
						value: 0
					}, {
						label: '1%',
						value: 1
					}, {
						label: '2%',
						value: 2
					}, {
						label: '3%',
						value: 3
					}, {
						label: '4%',
						value: 4
					}, {
						label: '5%',
						value: 5
					}, {
						label: '6%',
						value: 6
					}, {
						label: '7%',
						value: 7
					}, {
						label: '8%',
						value: 8
					}, {
						label: '9%',
						value: 9
					}, {
						label: '10%',
						value: 10
					}, {
						label: '11%',
						value: 11
					}, {
						label: '12%',
						value: 12
					}, {
						label: '13%',
						value: 13
					}, {
						label: '14%',
						value: 14
					}]
				],
				purposes: purposes,
			}
		},
		onLoad(opthon) {
			console.log("opthon ==> {}", opthon);
			//1.出借人 0.借款人
			this.contract.kind = opthon.kind
			if (this.contract.kind == 1) {
				this.prompt = '借款方';
			} else {
				this.prompt = '出借方';
			}
		},
		methods: {
			check() {
				if (!this.contract.userName || !this.contract.userCardNo) {
					uni.$u.toast("请填写对方信息")
					return
				}
				if (!this.contract.money) {
					uni.$u.toast("请填写借款金额")
					return
				} else {
					if (this.contract.money <= 0) {
						uni.$u.toast("借款金额不能为0元")
						return
					}
				}
				// if (this.contract.moneyRate <= 0) {
				// 	uni.$u.toast("请填写借款利率")
				// 	return
				// }
				if (!this.contract.loanDate) {
					uni.$u.toast("请选择借款日期")
					return
				}
				if (!this.contract.repayment) {
					uni.$u.toast("请选择还款日")
					return
				}
				if (!this.contract.purpose) {
					uni.$u.toast("请选择借款用途")
					return
				}


				if (!this.isCheckPay) {
					this.showPayPassword = true
				} else {
					let remark = '总还款金额:' + this.computedTotalMoney + "元";
					remark = remark + ", 还款日为: " + this.contract.repayment + '。';
					this.contract.remark = remark;
					this.save();
				}

			},
			confirm() {
				let data = {
					payPassword: this.payPassword
				}
				checkPayPassword(data).then(res => {
					if (res.code == 200) {
						this.isCheckPay = true
						this.showPayPassword = false
						this.check();
					}
				})
			},
			valChange(e) {
				console.log("借款金额 ==> {}", e);

			},
			selectLoanDate() {
				// 更新日期限制，确保每次打开选择器时都使用最新的当前日期
				this.minLoanDate = Date.now();
				this.maxLoanDate = Date.now() + 90 * 24 * 60 * 60 * 1000; // 3个月 = 90天
				this.showLoanDate = true;
			},
			confirmLoanDate(e) {
				console.log("选择借款日期 ==> {}, {}", e.value, e.mode);
				this.contract.loanDate = uni.$u.date(e.value, 'yyyy-mm-dd')
				this.cancelLoanDate()

			},
			cancelLoanDate() {
				this.showLoanDate = false
			},
			selectDate() {
				this.showData = true
			},
			save() {
				this.contract.totalMoney = this.computedTotalMoney;
				saveContract(this.contract).then(res => {
					console.log("提交成功");
					if (res.code == 200) {
						this.contract.id = res.data.id
						this.contract.signNo = res.data.signNo
						uni.$u.route('/pages/contract/share', {
							id: res.data.signNo
						});
						// 	uni.$u.route({
						// 		type: 'reLaunch',
						// 		url: 'pages/contract/fx',
						// 		params: {
						// 			id: res.data.id,
						// 			creditor: res.data.creditor,
						// 			debtor: res.data.debtor,
						// 			money: res.data.money,
						// 			moneyRate: res.data.moneyRate,
						// totalMoney: res.data.totalMoney
						// 		}
						// })
					} else {
						uni.$u.toast(res.msg)
					}

				})
			},
			confirmData(e) {
				console.log("选择日期 ==> {}, {}", e.value, e.mode);
				console.log("转换日期 ==> {}", uni.$u.date(e.value, 'yyyy-mm-dd'));
				let repaymentDate = new Date(e.value);
				let loanDate = new Date(this.contract.loanDate);
				if (repaymentDate <= loanDate) {
					uni.$u.toast('还款日必须大于借款时间');
					return;
				}
				this.contract.repayment = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')

				this.showData = false;
			},
			cancelDate() {
				this.showData = false
			},
			toAddUserPage() {
				uni.$u.route('/pages/contract/addUser', {
					userName: this.contract.userName,
					userCardNo: this.contract.userCardNo,
					userTele: this.contract.userTele
				});
			},
			setUserMsg(data) {
				console.log('收到子页面传来的数据:', data);
				this.contract.userName = data.userName
				this.contract.userCardNo = data.userCardNo
				this.contract.userTele = data.userTele
			},
			confirmRates(e) {
				console.log("利率 ==> {}", e);
				this.contract.moneyRate = e.value[0].value
				this.closeRates()

			},
			closeRates() {
				this.showRates = false
			},
			confirmPurpose(e) {
				this.purpose = e.value[0].label
				this.contract.purpose = e.value[0].value
				this.closePurpose()
			},
			closePurpose() {
				this.showPurpose = false
			},

		},
		computed: {
			computedTotalMoney() {
				const money = this.contract.money;
				const moneyRate = this.contract.moneyRate;
				const loanDate = this.contract.loanDate;
				const repayment = this.contract.repayment;

				if (money && moneyRate && loanDate && repayment) {
					const startDate = new Date(loanDate);
					const endDate = new Date(repayment);

					if (endDate < startDate) {
						uni.$u.toast("还款日期不能早于借款日期");
						return 0; // 或者其他错误处理
					}

					const diffInTime = endDate.getTime() - startDate.getTime();
					const diffInDays = Math.ceil(diffInTime / (1000 * 3600 * 24));

					const interest = money * (moneyRate / 100) * (diffInDays / 365);
					const totalRepayment = parseInt(money) + parseFloat(interest);
					return Math.round(totalRepayment * 100) / 100;
				} else if (money) {
					return money;
				}
				return 0;
			}
		}
	}
</script>

<style scoped>
	.from-title {
		height: 20px;
		margin-left: 20px;
		margin-top: 20px;

		display: flex;
		align-items: center;
	}

	.from-title>image {
		width: 5%;
		height: 100%;
	}

	.from-title-text {
		color: #54545C;
		font-size: 30rpx;
		font-weight: bold;
	}

	.from-item {
		margin-top: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.card_lx {
		margin-top: 30px;
		height: 40px;
		background-color: #fff;

		border-radius: 8px;
		border: 1px solid #c1c1c1;
	}
</style>